import logging
import time

from src.android.adb.control import Control
from src.android.uiauto.drive import UIAutoControlClass
from src.business.qian_niu import QianNiuApp
from src.common.prj_path import get_abs_path
from src.common.read_ini import read_ini
from src.common.utils import read_yaml

LOG = logging.getLogger()


class RunAutoScript(object):

    def __init__(self):
        self.yaml_path = get_abs_path('scripts', 'qian_niu.yaml')
        self.mobile_config_path = get_abs_path('settings', 'mobile_config.ini')
        self.yaml_dict = read_yaml(self.yaml_path)
        self.mobile_ip = self.get_mobile_ip()
        self.adb_control = Control()
        self.uiauto_control = UIAutoControlClass(self.mobile_ip)
        self.order_dict = {}

    def get_mobile_ip(self):
        ini_dict = read_ini(self.mobile_config_path)
        return ini_dict['global']['ip']

    def run_yaml_script(self):
        for item, value in self.yaml_dict.items():
            function = getattr(self.uiauto_control, value['function'])
            args = value['args'].split(',')
            function(*args)

    def get_order_dict(self):
        time.sleep(3)
        text_list = self.uiauto_control.get_all_text()
        LOG.info('wait_send_page text={}'.format(text_list))
        self.order_dict = get_order_dict(text_list)
        LOG.info("order_dict={}".format(self.order_dict))

    def delivery(self):
        for order in self.order_dict.values():
            send_text = QianNiuApp(order['product_name']).get_send_text()
            LOG.info("{} buyer send_text is {}".format(order['buyer'], send_text))

    def run(self):
        self.adb_control.unlock_phone()
        self.run_yaml_script()
        self.get_order_dict()
        self.delivery()


if __name__ == '__main__':
    a = RunAutoScript()
    a.run()
